import 'dart:async';
import 'dart:convert' as convert;
import 'dart:core';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/generated/intl/messages_en.dart';

import 'package:flutter_syt/utils/utils_dlog.dart';

// import 'package:flutter_webview_pro/webview_flutter.dart' as pro;
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/message_model.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/mine/service/service_socket.dart';
import 'package:flutter_syt/domain/waystation/map_helper.dart';
import 'package:flutter_syt/domain/widgets/photo_views_more_screen.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/fade_route.dart';
import 'package:flutter_syt/utils/map_navigator_util.dart';
import 'package:flutter_syt/utils/permission_helper.dart';
import 'package:flutter_syt/utils/screen_adapter.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/loading_widget.dart';
import 'package:flutter_syt/widgets/marquee_view.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:webview_flutter/webview_flutter.dart';

// import 'package:webview_pro_android/webview_android_widget.dart';
// import 'package:webview_flutter/webview_flutter.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../global_easy_loading.dart';

@RoutePage(name: "webDetail")
class WebDetailPage extends StatefulWidget {
  final String url;
  bool needBar = true;
  bool isUseUserAgent = false;
  bool openCheckPhotos;
  final Function(String title)? titleCall;
  var currentJson = Map<String, String>(); //当前执行的JS事件参数
  WebDetailPage(this.url, {this.titleCall, this.openCheckPhotos = true});

  @override
  State<StatefulWidget> createState() {
    return _WebDetailState();
  }
}

class WebContent extends WebDetailPage {
  final Function(String title)? titleCall;

  @override
  bool get needBar => false; //当前执行的JS事件参数
  WebContent(String url, {this.titleCall}) : super(url);

  @override
  State<StatefulWidget> createState() {
    return _WebDetailState();
  }
}

class _WebDetailState extends State<WebDetailPage> with RouteAware {
  bool isLoading = true;
  bool isGetTitle = false;
  String? _error;

  final WebViewController _controller = WebViewController();

  // final Completer<WebViewController> _controller1 =
  //     Completer<WebViewController>();
  bool initLocation = false;
  TapDownDetails? _downDetailsPress;
  bool isLongGes = false;
  bool _isGetTitle = true;

  // String? navigationUrl;
  // bool isLoading = false;

  @override
  void initState() {
    super.initState();
    _initializeWebView();
    GlobalData.data.addListener(_doNotify);
  }

  void _initializeWebView() {
    _controller
      ..setOnConsoleMessage((messages) {
        DLog('setOnConsoleMessage  ${messages.message}');
      })
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(_createNavigationDelegate())
      ..loadRequest(Uri.parse(widget.url));
    // _controller.
    addJavaScriptChannel();
  }

  NavigationDelegate _createNavigationDelegate() {
    return NavigationDelegate(
      onProgress: (int progress) {
        // Update loading bar.
      },
      onPageStarted: (String url) {
        DLog('web加载开始了11   $url');
        _error = null;
      },
      onPageFinished: (String url) {
        DLog('web加载完了');
        if (mounted) {
          setState(() {
            isLoading = false;
          });
        }
        _updateTitle();
      },
      onHttpError: (HttpResponseError error) {
        DLog('onHttpError   ${error.response}');
        _error = null;
      },
      onWebResourceError: (WebResourceError webError) {
        DLog(
            'web加载完了 报错了: ${webError.errorType.toString()}   ${webError.errorCode}');
      },
      onNavigationRequest:
          // widget.url.contains('client=app')
          //     ? null
          //     :

          (NavigationRequest navigation) {
        DLog('navigationDelegate: ${navigation.url}');
        if (navigation.url == 'about:blank') {
          return NavigationDecision.prevent;
        } else if (!navigation.url.startsWith("http")) {
          DLog("即将打开 ${navigation.url}");
          launchUrlString(navigation.url);
          return NavigationDecision.prevent;
        }
        return NavigationDecision.navigate;
      },
    );
  }

  void _updateTitle() {
    if (_isGetTitle) {
      Future.delayed(Duration(milliseconds: 100), () async {
        var t = await _controller.getTitle();
        // DLog('nativeUpdateTitle11  ${t}');
        if (!(t ?? '').contains('http')) {
          widget.titleCall?.call(_title);
          _isGetTitle = false;
          if (_title.isEmpty && mounted) {
            setState(() {
              _title = t ?? "";
            });
          }
        }
      });
    }
  }

  addJavaScriptChannel() {
    _controller.addJavaScriptChannel(
      'checkFullSize',
      onMessageReceived: (message) {
        // var str = message.message.toString();
        // customShowToast(str);
        DLog('addJavaScriptChannel  checkFullSize ${message.message}');
        var str = message.message.toString();

        if (str.isNotEmpty) {
          Map<String, dynamic> json = convert.jsonDecode(str);
          DLog(json);
          if (json.keys.contains('urls')) {
            List<String> lists = [];
            json['urls'].forEach((element) {
              lists.add(element.toString());
            });

            Navigator.of(context).push(
              FadeRoute(
                  page: PhotoViewMoreScreen(
                imageRows: lists,
                defaultImage: int.parse('${json['default'] ?? 0}'),
              )),
            );
          }
        }
      },
    );
    _controller.addJavaScriptChannel('toCustomer',
        onMessageReceived: (message) {
      GoodsInfoContentModel? model;
      DLog('addJavaScriptChannel  toCustomer ${message.message}');
      try {
        var str = message.message.toString();

        if (str.isNotEmpty) {
          Map<String, dynamic> json = convert.jsonDecode(str);
          model = GoodsInfoContentModel.fromJson(json);
        }
      } catch (e) {}
      // if (ServiceSocket.isOpen) {
      //   Navigator.pop(context);
      // } else {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => ServiceSocket(
                  'mall',
                  infoContentModel: model,
                  // isClickOpenWeb: false,
                )),
      ).then((value) {
        if (value != null &&
            value is Map &&
            value.keys.toList().contains('goodsUrl')) {
          _controller.loadHtmlString(value['goodsUrl']);
        }
      });
    });

    _controller.addJavaScriptChannel('nativeLogin',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeLogin ${message.message}');
      var str = message.message.toString();
      Map<String, dynamic> json = convert.jsonDecode(str);
      var appid = "${json["app_id"]}";
      var authUrl = "${json["auth_url"]}";
      var uid = "${json["uid"]}";
      // http://221.237.109.31:8052
      // eb2f6530-1d38-11ee-8b5c-8570f30318ae
      // var isClean = "${json["is_clean_cache"]}";
      _userAuth(uid, appid, authUrl);
    });
    // nativeUserlnfo is
    _controller.addJavaScriptChannel('nativeUserInfo',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeUserInfo ${message.message}');
      var str = message.message.toString();
      Map<String, dynamic> json = convert.jsonDecode(str);
      var uid = "${json["uid"]}";
      var result = '';
      if (UserInfo.me.isLogin) {
        result = '{"status":"1","message":"success","uid":"$uid",'
            '"data":{"nickname":"${UserInfo.me.nickname}","avatar":"${UserInfo.me.avatar}"}}';
      } else {
        result = '{"status":"0","message":"not login", "uid":"$uid"}';
      }
      _controller.runJavaScript("NATIVE2JS('${result}');");
    });
    _controller.addJavaScriptChannel('nativePay', onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativePay ${message.message}');
      var str = message.message.toString();

      Map<String, dynamic> json = convert.jsonDecode(str);
      var uid = "${json["uid"]}";
      var orderId = "${json["order_id"]}";
      _payAuth(orderId, uid);
    });
    _controller.addJavaScriptChannel('nativeUpdateTitle',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeUpdateTitle ${message.message}');
      var str = message.message.toString();
      Map<String, dynamic> json = convert.jsonDecode(str);
      // var appid = "${json["app_id"]}";
      var title = "${json["title"]}";
      DLog('nativeUpdateTitle  ${title}');
      if (title.isNotEmpty) {
        setState(() {
          _title = title;
          if (widget.titleCall != null) {
            widget.titleCall!(_title);
          }
        });
      }
    });
    _controller.addJavaScriptChannel('nativeClosePage',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeClosePage ${message.message}');
      _closePage();
    });
    _controller.addJavaScriptChannel('nativeTopBarHeight',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeTopBarHeight ${message.message}');
      var str = message.message.toString();
      Map<String, dynamic> json = convert.jsonDecode(str);
      var uid = "${json["uid"]}";
      var result = '{"status":"1","message":"success","uid":"$uid",'
          '"data":{"height":"${ScreenAdapter.padTopH()}"}}';
      _controller.runJavaScript("NATIVE2JS('$result');");
    });
    _controller.addJavaScriptChannel('nativeUserLocation',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeUserLocation ${message.message}');
      if (!initLocation) {
        DLog('%%%%%%%%%%%%%%%%%%%%%%');
        initLocation = true;
        var str = message.message.toString();
        Map<String, dynamic> json = convert.jsonDecode(str);
        var uid = "${json["uid"]}";
        // LocationHelper.instance.result((event) async {
        //   if (event.isLocationSuccess) {
        //     var result =
        //         '{"data":{"latitude":"${event.location?.latitude ?? ''}","longitude":"${event.location?.longitude ?? ''}"},"uid":"$uid","status":"1"}';
        //     _controller.runJavaScript("NATIVE2JS('$result');");
        //     initLocation = false;
        //   } else {
        //     var result =
        //         '{"data":{"latitude":"0","longitude":"0","uid":"$uid"},"status":"0"}';
        //     _controller.runJavaScript("NATIVE2JS('$result');");
        //     initLocation = false;
        //   }
        // });
        // LocationHelper.instance.startLocation();
      }
    });
    _controller.addJavaScriptChannel('nativeUserMicrophone',
        onMessageReceived: (message) async {
      DLog('addJavaScriptChannel  nativeUserMicrophone ${message.message}');
      // bool isSuccess =
      //     await PermissionHelper.checkMicrophonePermission(context);
      // var result = '{"status":"${isSuccess ? 1 : 0}"}';
      // _controller?.evaluateJavascript("NATIVE2JS('$result');");
      // _controller.runJavaScript("NATIVE2JS('$result');");

    });
    _controller.addJavaScriptChannel('nativeToPage',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeToPage ${message.message}');
      try {
        var str = message.message.toString();
        Map<String, dynamic> json = convert.jsonDecode(str);
        _toNativePage(json);
      } catch (e) {
        if (e is DioError && !(e.error is SocketException)) {
          customShowToast(e.message ?? '');
        }
      }
    });
    _controller.addJavaScriptChannel('nativeToMap',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeToMap ${message.message}');
      try {
        var str = message.message.toString();
        Map<String, dynamic> json = convert.jsonDecode(str);
        // _toNativePage(json);
        MapNavigatorUtil.showBottom(context,
            longitude: json['longitude'].toString(),
            latitude: json['latitude'].toString());
      } catch (e) {
        if (e is DioError && !(e.error is SocketException)) {
          customShowToast(e.message ?? '');
        }
      }
    });
    _controller.addJavaScriptChannel('nativeShareLink',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeShareLink ${message.message}');
      try {
        var str = message.message.toString();
        Map<String, dynamic> json = convert.jsonDecode(str);
        var uid = "${json["uid"]}";
        try {
          var shareJson = json["share_config"] as Map<String, dynamic>;
          var title = shareJson["title"] as String;
          var text = shareJson["text"] as String;
          var link = shareJson["link_url"] as String;
          Share.shareUri(Uri.parse(link));
          var result = '{"status":"1","message":"success","uid":"$uid"}';
          _controller.runJavaScript("NATIVE2JS('$result');");
        } catch (e) {
          var msg = "$e";
          if (e is DioError) {
            msg = e.message ?? '';
          }
          var failed = '{"status":"0","message":"$msg","uid":"$uid"}';
          _controller.runJavaScript("NATIVE2JS('$failed');");
        }
      } catch (e) {
        if (e is DioError) {
          customShowToast(e.message ?? '');
        }
      }
    });
  }

  @override
  void dispose() {
    appContext.rootObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    var route = ModalRoute.of<dynamic>(context);
    if (route != null) {
      appContext.rootObserver.subscribe(this, route);
    }
    super.didChangeDependencies();
  }

  @override
  void didPopNext() {
    // 在登录页返回，或者支付页返回时回调。
    super.didPopNext();
    _doNotify();
  }

  void _doNotify() async {
    if (GlobalData.loaginCallback) {
      var uid = "${widget.currentJson['uid']}";
      var appId = "${widget.currentJson['appId']}";
      var authUrl = "${widget.currentJson['authUrl']}";
      // var isClean = "${widget.currentJson["is_clean_cache"]}";
      if (UserInfo.me.isLogin) {
        _userAuth(uid, appId, authUrl);
      } else {
        if (mounted) {
          if (await _controller?.canGoBack() == true) {
            // _controller?.goBack();
          } else {
            Future.delayed(Duration(milliseconds: 300), () {
              Navigator.pop(context);
            });
          }
        }
      }
      GlobalData.loaginCallback = false;
      GlobalData.pageFrom = '';
    }
    widget.currentJson.clear();
    // customShowToast(status)
  }

  Widget loading() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "assets/icons/empty.png",
            width: 80,
            height: 80,
          ),
          Container(
            height: 12,
          ),
          Text(
            S.of(context).loading,
            style:
                TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14),
          ),
          Container(
            height: 20,
          ),
        ],
      ),
    );
  }

// JS获取登录信息，未登录时登录后完成操作。
  void _userAuth(
    String uid,
    String appId,
    String authUrl,
  ) async {
    void doAuth() async {
      try {
        var json = await API.shared.bridge.authorize(
          appId,
          authUrl,
          // isClean
        );
        //
        var code = "${json["code"]}";
        var openid = "${json["openid"]}";
        var iscleancache = "${json["is_clean_cache"]}";
        var result = "";
        if (code != 'null') {
          result =
              '{"status":"1","message":"success","uid":"$uid","data":{"uid":"$uid","code":"$code","openid":"$openid","iscleancache":"$iscleancache"}}';
        } else {
          result = '{"status":"0","message":"code is null", "uid":"$uid"}';
        }
// _controller.runJavaScript(javaScript)
        _controller.runJavaScript("NATIVE2JS('$result');");
      } catch (e, stack) {
        var msg = S().network_error;
        if (e is DioError && !(e.error is SocketException)) {
          msg = e.message ?? '';
          // if (e.response?.statusCode != 401) {
          customShowError(msg);
          // }
        } else {
          customShowError(msg);
        }

        var failed = '{"status":"0","message":"$msg", "uid":"$uid"}';
        _controller.runJavaScript("NATIVE2JS('$failed');");
      }
    }

    if (UserInfo.me.isLogin) {
      doAuth();
    } else {
      GlobalData.loaginCallback = true;
      widget.currentJson['uid'] = uid;
      widget.currentJson['appId'] = appId;
      widget.currentJson['authUrl'] = authUrl;
      GlobalData.pageFrom = "web_detail";
      RouteManager.push(context, RoutMapping.loginByPwd()).then((value) {
        if (UserInfo.me.isLogin != true) {
          // Navigator.pop(context);
        }
      });
    }
  }

// 支付
  void _payAuth(String orderId, String uid) async {
    try {
      var json = await API.shared.bridge.prePayOrderInfo(orderId);
      json['order_id'] = orderId;
      var pushData =
          '{"order_id":"$orderId","total_fee":"${json["total_fee"]}", "body":"${json["body"]}", "pay_mode": "${json["pay_mode"]}"}';
      widget.currentJson['uid'] = uid;
      DLog(pushData);
      RouteManager.push(context, RoutMapping.paymentDesk(pushData))
          .then((value) {
        var msg = '0';
        try {
          msg = value.result as String;
        } catch (e) {}
        var result = '';
        if (msg == '1') {
          result = '{"status":"1", "uid":"$uid"}';
        } else {
          result = '{"status":"0", "uid":"$uid"}';
        }
        _controller.runJavaScript("NATIVE2JS('$result');");
      });
    } catch (e, stack) {
      UtilsOther.showCustomShowError(e);
      var failed = '{"status":"0","message":"$e","uid":"$uid"}';
      _controller.runJavaScript("NATIVE2JS('$failed');");
    }
  }

  void _toNativePage(Map<String, dynamic> data) {
    var uid = "${data["uid"]}";
    try {
      var pageJson = data["router"] as Map<String, dynamic>;
      var pageType = pageJson["page_type"] as String;
      if (pageType == 'match_detail') {
        var id = "${pageJson["page_id"]}";
        if (id != 'null' && id.isNotEmpty) {
          var result = '{"status":"1", "uid":"$uid"}';
          _controller.runJavaScript("NATIVE2JS('$result');");
          RouteManager.push(
              context, RoutMapping.gameDetail(id, isVideo: false));
        }
      }
    } catch (e) {
      var failed =
          '{"status":"0","message":"${S.of(context).pay_no_support}","uid":"$uid"}';
      _controller.runJavaScript("NATIVE2JS('$failed');");
    }
  }

  void _closePage() {
    // DLog('close page');
    Navigator.pop(context);
    // if (Navigator.canPop(context)) {
    //   Navigator.pop(context);
    // }
  }

  void _back() async {
    var can = await _controller.canGoBack();
    if (can == true) {
      _controller.goBack();
    } else {
      _closePage();
    }
  }

  Future<bool> _requestPop() async {
    //这里是回调函数
    // print("POP");
    if (Platform.isIOS) {
      return true;
    } else {
      var can = await _controller.canGoBack();
      if (can == true) {
        _controller.goBack();
      } else {
        _closePage();
      }
    }
    return Future.value(false);
  }

  var _title = '';

  @override
  Widget build(BuildContext context) {
    return Platform.isIOS
        ? buildMainView()
        : WillPopScope(onWillPop: _requestPop, child: buildMainView());
  }

  Widget buildMainView() {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: _buildAppBar(),
      body: _buildBody(),
    );
  }

  AppBar? _buildAppBar() {
    if (!widget.needBar && _error == null) return null;
    return AppBar(
      titleSpacing: 0.0,
      title: _buildAppBarTitle(),
      automaticallyImplyLeading: false,
      centerTitle: true,
    );
  }

  Row _buildAppBarTitle() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: ClickUtils.debounce(() => {_back()}),
        ),
        IconButton(
          icon: Icon(Icons.close),
          onPressed: ClickUtils.debounce(() => {_closePage()}),
        ),
        Expanded(
          child: Visibility(
            visible: _error == null && !isLoading,
            child: Center(
              child: UtilsOther.boundingTextSize(_title, TextStyle()).width >
                      (1.sw - 200)
                  ? MarqueeView(title: _title)
                  : Text(_title),
            ),
          ),
        ),
        Container(width: 96, height: 40),
      ],
    );
  }

  Widget _buildBody() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.white,
      child:  buildWebViewFlutter(),
    );
  }

  // GestureDetector _buildGestureDetector() {
  //   return GestureDetector(
  //     onTapDown: (details) {
  //       DLog('onTapDown');
  //       _downDetailsPress = details;
  //     },
  //     onLongPress: _handleLongPress,
  //     child: buildWebViewFlutter(),
  //   );
  // }
  //
  // void _handleLongPress() {
  //   if (!isLoading && _error == null) {
  //     isLongGes = false;
  //     if (_downDetailsPress != null) {
  //       String script = '''
  //         (function() {
  //           var element = document.elementFromPoint(${_downDetailsPress?.localPosition.dx}, ${_downDetailsPress?.localPosition.dy});
  //           if (element && element.tagName === 'IMG') {
  //             return element.src;
  //           }
  //           return null;
  //         })();
  //       ''';
  //
  //       // _controller.runJavaScriptReturningResult(script).then((value) {
  //       //   DLog('获取到的图片地址: $value');
  //       //   // ''.contains(other)
  //       //   if (value is String && value.isNotEmpty && !value.contains('null')) {
  //       //     UtilsOther.showBottomSaveImage( image: value);
  //       //     // UtilsOther.showPopupMeun(
  //       //     //     _downDetailsPress!.globalPosition, value, context);
  //       //   }
  //       // });
  //     }
  //   }
  // }

  Widget buildWebViewFlutter() {
    return Stack(
      children: [
        Positioned.fill(
            child: WebViewWidget(
          controller: _controller,
          //  initialCookies: [],
          // onWebViewCreated: (controller) {
          //   _controller = controller;
          //   DLog("############${widget.url}");
          //   // appContext.webController = controller;
          //   // _controller?.clearCache();
          // },
          // initialUrl: widget.url,
          // debuggingEnabled: true,
          // allowsInlineMediaPlayback: true,
          // // zoomEnabled: true,
          //
          // // geolocationEnabled: true,
          // userAgent: widget.isUseUserAgent ? "wisdom Universiade" : "",
          // javascriptMode: JavascriptMode.unrestricted,
          // javascriptChannels: {
          //   JavascriptChannel(
          //     name: "checkFullSize",
          //     onMessageReceived: (message) {
          //       // var str = message.message.toString();
          //       // customShowToast(str);
          //       var str = message.message.toString();
          //
          //       if (str.isNotEmpty) {
          //         Map<String, dynamic> json = convert.jsonDecode(str);
          //         DLog(json);
          //         if (json.keys.contains('urls')) {
          //           List<String> lists = [];
          //           json['urls'].forEach((element) {
          //             lists.add(element.toString());
          //           });
          //
          //           Navigator.of(context).push(
          //             FadeRoute(
          //                 page: PhotoViewMoreScreen(
          //                   imageRows: lists,
          //                   defaultImage: int.parse('${json['default'] ?? 0}'),
          //                 )),
          //           );
          //         }
          //       }
          //     },
          //   ),
          //
          //   JavascriptChannel(
          //       name: "toCustomer",
          //       onMessageReceived: (message) {
          //         GoodsInfoContentModel? model;
          //
          //         try {
          //           var str = message.message.toString();
          //
          //           if (str.isNotEmpty) {
          //             Map<String, dynamic> json = convert.jsonDecode(str);
          //             model = GoodsInfoContentModel.fromJson(json);
          //           }
          //         } catch (e) {}
          //         // if (ServiceSocket.isOpen) {
          //         //   Navigator.pop(context);
          //         // } else {
          //         Navigator.push(
          //           context,
          //           new MaterialPageRoute(
          //               builder: (context) => ServiceSocket(
          //                 'mall',
          //                 infoContentModel: model,
          //                 // isClickOpenWeb: false,
          //               )),
          //         ).then((value) {
          //           if (value != null &&
          //               value is Map &&
          //               value.keys.toList().contains('goodsUrl')) {
          //             _controller?.loadUrl(value['goodsUrl']);
          //           }
          //         });
          //       }),
          //   // 获取本地的appcode
          //   JavascriptChannel(
          //       name: "nativeLogin",
          //       onMessageReceived: (message) {
          //         var str = message.message.toString();
          //         Map<String, dynamic> json = convert.jsonDecode(str);
          //         var appid = "${json["app_id"]}";
          //         var authUrl = "${json["auth_url"]}";
          //         var uid = "${json["uid"]}";
          //         // http://221.237.109.31:8052
          //         // eb2f6530-1d38-11ee-8b5c-8570f30318ae
          //         // var isClean = "${json["is_clean_cache"]}";
          //         _userAuth(uid, appid, authUrl);
          //       }),
          //   // 获取登录后的用户信息，未登录返空
          //   JavascriptChannel(
          //       name: "nativeUserInfo",
          //       onMessageReceived: (message) {
          //         var str = message.message.toString();
          //         Map<String, dynamic> json = convert.jsonDecode(str);
          //         var uid = "${json["uid"]}";
          //         var result = '';
          //         if (UserInfo.me.isLogin) {
          //           result = '{"status":"1","message":"success","uid":"$uid",'
          //               '"data":{"nickname":"${UserInfo.me.nickname}","avatar":"${UserInfo.me.avatar}"}}';
          //         } else {
          //           result =
          //           '{"status":"0","message":"not login", "uid":"$uid"}';
          //         }
          //         _controller?.runJavascript("NATIVE2JS('${result}');");
          //         // if (!UserInfo.me.isLogin) {
          //         //   Navigator.pop(context);
          //         // }
          //       }),
          //   // 本地支付跳转，目前只用作于测试调试
          //   JavascriptChannel(
          //       name: "nativePay",
          //       onMessageReceived: (message) {
          //         var str = message.message.toString();
          //         Map<String, dynamic> json = convert.jsonDecode(str);
          //         var uid = "${json["uid"]}";
          //         var orderId = "${json["order_id"]}";
          //         _payAuth(orderId, uid);
          //       }),
          //   JavascriptChannel(
          //       name: "nativeUpdateTitle",
          //       onMessageReceived: (message) {
          //         var str = message.message.toString();
          //         Map<String, dynamic> json = convert.jsonDecode(str);
          //         // var appid = "${json["app_id"]}";
          //         var title = "${json["title"]}";
          //         DLog('nativeUpdateTitle  ${title}');
          //         if (title.isNotEmpty) {
          //           setState(() {
          //             _title = title;
          //             if (widget.titleCall != null) {
          //               widget.titleCall!(_title);
          //             }
          //           });
          //         }
          //       }),
          //   JavascriptChannel(
          //       name: "nativeClosePage",
          //       onMessageReceived: (message) {
          //         _closePage();
          //       }),
          //   JavascriptChannel(
          //       name: "nativeTopBarHeight",
          //       onMessageReceived: (message) {
          //         var str = message.message.toString();
          //         Map<String, dynamic> json = convert.jsonDecode(str);
          //         var uid = "${json["uid"]}";
          //         var result = '{"status":"1","message":"success","uid":"$uid",'
          //             '"data":{"height":"${ScreenAdapter.padTopH()}"}}';
          //         _controller?.runJavascript("NATIVE2JS('$result');");
          //       }),
          //   JavascriptChannel(
          //       name: "nativeUserLocation",
          //       onMessageReceived: (message) {
          //         if (!initLocation) {
          //           DLog('%%%%%%%%%%%%%%%%%%%%%%');
          //           initLocation = true;
          //           var str = message.message.toString();
          //           Map<String, dynamic> json = convert.jsonDecode(str);
          //           var uid = "${json["uid"]}";
          //           LocationHelper.instance.result((event) async {
          //             if (event.isLocationSuccess) {
          //               var result =
          //                   '{"data":{"latitude":"${event.location?.latitude ?? ''}","longitude":"${event.location?.longitude ?? ''}"},"uid":"$uid","status":"1"}';
          //               _controller?.runJavascript("NATIVE2JS('$result');");
          //               initLocation = false;
          //             } else {
          //               var result =
          //                   '{"data":{"latitude":"0","longitude":"0","uid":"$uid"},"status":"0"}';
          //               _controller?.runJavascript("NATIVE2JS('$result');");
          //               initLocation = false;
          //             }
          //           });
          //           LocationHelper.instance.startLocation();
          //         }
          //       }),
          //   JavascriptChannel(
          //       name: "nativeUserMicrophone",
          //       onMessageReceived: (message) async {
          //         // customShowToast('接收到nativeUserMicrophone事件');
          //         bool isSuccess =
          //         await PermissionHelper.checkMicrophonePermission(context);
          //         var result = '{"status":"${isSuccess ? 1 : 0}"}';
          //         // _controller?.evaluateJavascript("NATIVE2JS('$result');");
          //         _controller?.runJavascript("NATIVE2JS('$result');");
          //         // runJavascript
          //       }),
          //   JavascriptChannel(
          //       name: "nativeToPage",
          //       onMessageReceived: (message) {
          //         try {
          //           var str = message.message.toString();
          //           Map<String, dynamic> json = convert.jsonDecode(str);
          //           _toNativePage(json);
          //         } catch (e) {
          //           if (e is DioError && !(e.error is SocketException)) {
          //             customShowToast(e.message);
          //           }
          //         }
          //       }),
          //   JavascriptChannel(
          //       name: "nativeToMap",
          //       onMessageReceived: (message) {
          //         try {
          //           var str = message.message.toString();
          //           Map<String, dynamic> json = convert.jsonDecode(str);
          //           // _toNativePage(json);
          //           MapNavigatorUtil.showBottom(context,
          //               longitude: json['longitude'].toString(),
          //               latitude: json['latitude'].toString());
          //         } catch (e) {
          //           if (e is DioError && !(e.error is SocketException)) {
          //             customShowToast(e.message);
          //           }
          //         }
          //       }),
          //   JavascriptChannel(
          //       name: "nativeShareLink",
          //       onMessageReceived: (message) {
          //         try {
          //           var str = message.message.toString();
          //           Map<String, dynamic> json = convert.jsonDecode(str);
          //           var uid = "${json["uid"]}";
          //           try {
          //             var shareJson =
          //             json["share_config"] as Map<String, dynamic>;
          //             var title = shareJson["title"] as String;
          //             var text = shareJson["text"] as String;
          //             var link = shareJson["link_url"] as String;
          //             FlutterShare.share(
          //                 title: title, text: text, linkUrl: link);
          //             var result =
          //                 '{"status":"1","message":"success","uid":"$uid"}';
          //             _controller?.runJavascript("NATIVE2JS('$result');");
          //           } catch (e) {
          //             var msg = "$e";
          //             if (e is DioError) {
          //               msg = e.message;
          //             }
          //             var failed =
          //                 '{"status":"0","message":"$msg","uid":"$uid"}';
          //             _controller?.runJavascript("NATIVE2JS('$failed');");
          //           }
          //         } catch (e) {
          //           if (e is DioError) {
          //             customShowToast(e.message);
          //           }
          //         }
          //       }),
          // },
          // navigationDelegate: widget.url.contains('client=app')
          //     ? null
          //     : (NavigationRequest navigation) {
          //   // navigation.isForMainFrame
          //   DLog('navigationDelegate: ${navigation.url}');
          //   // navigationUrl = navigation.url;
          //   if (navigation.url == 'about:blank') {
          //     return NavigationDecision.prevent;
          //   } else if (!navigation.url.startsWith("http")) {
          //     DLog("即将打开 ${navigation.url}");
          //
          //     launchUrlString(navigation.url);
          //     return NavigationDecision.prevent;
          //   }
          //   return NavigationDecision.navigate;
          // },
          // onPageStarted: (result) async {
          //   // result
          //   DLog('web加载开始了   $result');
          //   _error = null;
          // },
          // onPageFinished: (result) async {
          //   // _isFinished = true;
          //   DLog('web加载完了');
          //
          //   if (mounted) {
          //     setState(() {
          //       // _error = null;
          //       isLoading = false;
          //     });
          //   }
          //
          //   if (_isGetTitle == true) {
          //     Future.delayed(Duration(milliseconds: 100), () async {
          //       var t = await _controller?.getTitle();
          //       DLog('nativeUpdateTitle11  ${t}');
          //       if (!(t ?? '').contains('http')) {
          //         if (widget.titleCall != null) {
          //           widget.titleCall!(_title);
          //         }
          //         _isGetTitle = false;
          //         if (_title.isEmpty) {
          //           if (mounted) {
          //             setState(() {
          //               _title = t ?? "";
          //             });
          //           }
          //         }
          //       }
          //     });
          //   }
          // },
          //
          // onWebResourceError: (webError) {
          //   DLog(
          //       'web加载完了 报错了: ${webError.description}   ${webError.errorCode}');
          //   if (webError.errorType ==
          //       WebResourceErrorType.webContentProcessTerminated) {
          //     _controller?.reload();
          //   } else if (webError.errorCode == -2) {
          //     // DLog(_error);
          //     if (mounted) {
          //       setState(() {
          //         isLoading = false;
          //         _error = S().load_failed;
          //       });
          //     }
          //   }
          // },
          // allowsInlineMediaPlayback: true,
        )),
        Positioned.fill(
            child: IgnorePointer(
              child: Visibility(
                  visible: isLoading,
                  child: Container(
                    color: Colors.white,
                    child: LoadingWidget(),
                  )),
            )),
        Positioned.fill(
            child: Visibility(
                visible: _error != null,
                child: Container(
                  color: Colors.white,
                  child: TextButton(
                    child: ViewStateEmptyWidget(
                      message: _error != null ? "$_error" : null,
                    ),
                    onPressed: ClickUtils.debounce(() async {
                      // _loadingGetData();
                      if (mounted) {
                        setState(() {
                          isLoading = true;
                          _error = null;
                        });
                      }
                      // _controller?.loadUrl(widget.url);
                      // _controller?.reload();
                      if (Platform.isIOS) {
                        _controller.loadRequest(Uri.parse(widget.url));
                      } else {
                        _controller.reload();
                      }
                      DLog('casdvds');
                    }),
                  ),
                )))
      ],
    );
  }
}
